package com.huatai.common.error;

/**
 * @program: ht-system
 * @description: 错误捕获
 * @author: songxiude
 * @create: 2023-01-31 17:10
 **/


import java.util.Map;

import com.huatai.common.api.R;
import com.huatai.common.api.ResultCode;
import com.huatai.common.util.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.WebRequest;

public class HtErrorAttributes extends DefaultErrorAttributes {
    private static final Logger log = LoggerFactory.getLogger(HtErrorAttributes.class);

    public HtErrorAttributes() {
    }

    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        String requestUri = (String)this.getAttr(webRequest, "javax.servlet.error.request_uri");
        Integer status = (Integer)this.getAttr(webRequest, "javax.servlet.error.status_code");
        Throwable error = this.getError(webRequest);
        R result;
        if (error == null) {
            log.error("URL:{} error status:{}", requestUri, status);
            result = R.fail(ResultCode.FAILURE, "系统未知异常[HttpStatus]:" + status);
        } else {
            log.error(String.format("URL:%s error status:%d", requestUri, status), error);
            result = R.fail(status, error.getMessage());
        }
        ErrorLogPublisher.publishEvent(error, requestUri);
        return BeanUtil.toMap(result);
    }

    @Nullable
    private <T> T getAttr(WebRequest webRequest, String name) {
        return (T) webRequest.getAttribute(name, 0);
    }
}

